package com.maxd.controller.userinfo;

import com.maxd.adapter.IgnoreSecurity;
import com.maxd.adapter.LoginRequired;
import com.maxd.adapter.LoginUserHolder;
import com.maxd.bean.user.AdjustPromotePointReq;
import com.maxd.error.ExceptionEnum;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.*;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.jifen.JiFenJpaRepository;
import com.maxd.respository.jifen.JiFenRepository;
import com.maxd.respository.money.MoneyDetailsJpaRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.jifen.IJiFenService;
import com.maxd.service.message.IMessageService;
import com.maxd.service.money.IMoneyDetailsService;
import com.maxd.service.userinfo.IUserService;
import com.maxd.service.userinfo.UserServiceImpl;
import com.maxd.service.wx.AccountService;
import com.maxd.utils.AdminUtils;
import com.maxd.utils.AssertUtil;
import com.maxd.utils.Config;
import com.maxd.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(value = "用户信息管理", tags = {"用户信息管理"})
@RequestMapping(value = "/user")
public class UserInfosController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private AccountService accountService;
    @Autowired
    private IMessageService iMessageService;
    @Autowired
    private IJiFenService jiFenService;
    @Autowired
    private JiFenJpaRepository jiFenRepository;
    @Autowired
    private JiFenRepository fenRepository;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private IMoneyDetailsService iMoneyDetailsService;
    @Autowired
    private MoneyDetailsJpaRepository moneyDetailsJpaRepository;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation("用户端和管理平台获取用户详情")
    @ResponseBody
    public Result getUserInfoById(@PathVariable Integer id) {
        return iUserService.findOne(Long.valueOf(id));
    }

    @RequestMapping(value = "/my-user-info", method = RequestMethod.GET)
    @ApiOperation("商城端获取自身的用户信息")
    @ResponseBody
    public Result<UserInfo> getUserInfoById() {
        Long userId = LoginUserHolder.getUserId();
        AssertUtil.assertTrue(userId != null && userId > 0, ExceptionEnum.WRONT_TOKEN);
        return iUserService.findOne(userId);
    }

    @PostMapping(value = "/adjust-promote-point")
    @ApiOperation("内管调整推广积分")
    @ResponseBody
    public Result<Void> adjustPromotePoint(@Validated @RequestBody AdjustPromotePointReq req) {
        AdminUtils.checkLogin();
        iUserService.adjustPromotePoint(req);
        return ResultUtil.success();
    }

    @GetMapping("/isSignIn")
    @ApiOperation("今天是否签到")
    public Result isSignIn(Long id){
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Long aLong = fenRepository.countJiFenByTime(sdf1.format(new Date()), String.valueOf(id));
        if(aLong==null){
            return ResultUtil.success();
        }else{
            return ResultUtil.error(-200,"今天已经签到过了");
        }

    }


    @PostMapping("/signIn")
    @ApiOperation("签到")
    @ResponseBody
    public Result signIn(Integer id){
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        //每日登陆签到
        Long countByTime = fenRepository.countJiFenLogin(sdf1.format(new Date()), String.valueOf(id));//统计积分数量
        if (countByTime == 0) {
            UserInfo userInfo = userJpaRepository.findById(Long.valueOf(id)).orElse(null);
            if (userInfo != null && userInfo.getRelationId() != null) {
                CommonInfo one = commonRepository.findOne(78);
                //获取昨天是否签到
                Date previouslyDay = DateUtil.getPreviouslyDay(new Date(), 1L);
                Long aLong = fenRepository.countJiFenByTime(sdf1.format(previouslyDay), String.valueOf(id));
                BigDecimal number=new BigDecimal("0.00");
                if(aLong!=null){
                    JiFen jiFen = jiFenRepository.findById(aLong).orElse(null);
                    number = new BigDecimal(jiFen.getNumber());
                    String day = commonRepository.findOne(291).getValue();
                    String num = commonRepository.findOne(292).getValue();
                    BigDecimal multiply = new BigDecimal(day).multiply(new BigDecimal(num));
                    BigDecimal add = multiply.add(new BigDecimal(one.getValue()));
                    if(number.doubleValue()>=add.doubleValue()){
                        number=add;
                    }else{
                        number=number.add(new BigDecimal(num));
                    }
                }else{
                    number=new BigDecimal(one.getValue());
                }
                double v = Double.parseDouble(one.getValue());
                double orderJifen = Float.parseFloat(userInfo.getOrderJifen());
                userInfo.setOrderJifen(String.valueOf(orderJifen + v));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date now = new Date();
                JiFen jiFen = new JiFen();
                jiFen.setCreateAt(sdf.format(now));
                jiFen.setContent("每日登录");
                jiFen.setDes(sdf1.format(new Date()) + "登录+" + one.getValue() + "积分");
                jiFen.setNumber(String.valueOf(number));
                jiFen.setUserId(String.valueOf(id));
                userJpaRepository.save(userInfo);
                jiFenRepository.save(jiFen);
            }
        }
        return ResultUtil.success();
    }


    @RequestMapping(value = "/getUserJifenList/{userId}", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("用户端获取用户积分")
    public Result getUserJifenList(@PathVariable Long userId) {
        return jiFenService.findList(userId);
    }

    @RequestMapping(value = "/cashMoney/{userId}", method = RequestMethod.GET)
    @ResponseBody

    @ApiOperation("用户端积分兑换钱币")
    public Result moneyCash(@PathVariable Long userId, @RequestParam String money) {
        UserInfo one = userJpaRepository.getOne(userId);
        DecimalFormat df = new DecimalFormat("#########.##");
        String orderJifen = one.getOrderJifen().toString();
        double m = Float.parseFloat(money);
        double i = Float.parseFloat(orderJifen);
        if(m>i){
            return ResultUtil.error(-100,"积分数量不足，请输入正确的积分数量");
        }
        //剩余积分
        double a = i - m;
        //计算金额
        double f1 = Float.parseFloat(df.format(m * 0.001));
        String ji = df.format(f1);
        String orderji = df.format(a);
        //保存可提现金额
        userRepository.updateJiFenAdd(ji,one.getId());
        //保存剩余积分
        userRepository.updateOrderJifen(orderji,one.getId());
       /* one.setJifen(f);
        //保存剩余积分
        one.setOrderJifen(df.format(a));*/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        JiFen jiFen = new JiFen();
        jiFen.setCreateAt(sdf.format(now));
        jiFen.setContent("积分兑换");
        jiFen.setDes("积分兑换-" + money);
        jiFen.setNumber(money);
        jiFen.setUserId(String.valueOf(userId));
//        userJpaRepository.save(one);
        iMoneyDetailsService.saveBody(one.getId(),1,2,"积分兑换","积分兑换金额，消耗积分："+m+",兑换金额："+ji,Double.parseDouble(ji));

        jiFenRepository.save(jiFen);
        return ResultUtil.success();
    }

    @RequestMapping(value = "/selectUserDetails", method = RequestMethod.GET)
    @ApiOperation("获取用户钱包明细")
    @ResponseBody
    public Result selectUserDetails(int page,int size,Long userId) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(iMoneyDetailsService.selectMoneyDetailsByUserId(pageable,userId));
    }

    @GetMapping("/userNumber")
    @IgnoreSecurity
    public Result userNumber() {
        List<UserInfo> all = userJpaRepository.findAll();
        for (UserInfo u : all) {
            if (u.getRelationId() != null) {
                u.setIsRelation(1);
                userJpaRepository.save(u);
            }
        }
        return ResultUtil.success();
    }

    /**
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteByUserId", method = RequestMethod.POST)
    @ApiOperation("删除用户")
    @ResponseBody
    public Result deleteById(Long userId) {
        //删除用户
        userJpaRepository.deleteById(userId);
        //删除用户关联积分表信息
        fenRepository.deleteJiFenByUserId(userId);
        return ResultUtil.success();
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/notification/{id}", method = RequestMethod.POST)
    @ApiOperation("管理平台消息推送")
    @ResponseBody
    public Result updateIsOut(@PathVariable Long id) {
        CommonInfo url = commonRepository.findOne(19);
        UserInfo one = userJpaRepository.findById(id).orElse(null);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        assert one != null;
        totalSuccess(one.getOpenId(), one.getNickName(), sdf1.format(new Date()), one.getJifen().toString(), one.getJifen().toString(), url.getValue());
        return ResultUtil.success();
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ApiOperation("用户端 APP中手机号密码注册")
    @ResponseBody
    public Result registerUser(@RequestBody UserInfo userInfo) {
        if (userInfo.getPhone().isEmpty()) {
            return ResultUtil.error(ExceptionEnum.USER_PHONE_ERROR);
        } else {
            UserInfo userByPhone = iUserService.getUserByPhone(userInfo.getPhone());
            if (userByPhone == null) {
                iUserService.saveBody(userInfo);
                return ResultUtil.success();
            } else {
                return ResultUtil.error(ExceptionEnum.USER_IS_EXITS);
            }
        }

    }

    @RequestMapping(value = "/page/{page}/{size}", method = RequestMethod.GET)
    @ApiOperation("管理平台用户列表")
    @ResponseBody
    public Result getBodyPage(@PathVariable Integer page, @PathVariable int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(userJpaRepository.findAll(pageable));
    }

    @RequestMapping(value = "/getCountNumber", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台累计总用户数")
    public Result getCountNumber() {
        return ResultUtil.success(userRepository.getCountNumber());
    }

    @RequestMapping(value = "/getCountNumber/{id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台会员用户和非会员用户总数")
    public Result getCountNumberMember(@PathVariable int id) {
        return ResultUtil.success(userRepository.getCountNumberMember(id));
    }

    @RequestMapping(value = "/findAllByRelationIdNotNull", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台统计淘宝授权用户")
    public Result findAllByRelationIdNotNull() {
        return ResultUtil.success(userJpaRepository.findAllByRelationIdNotNullOrderByIdDesc());
    }

    @RequestMapping(value = "/findAllByJifenNotNullOrderByIdDesc", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台获取普通用户")
    public Result findAllByJifenNotNullOrderByIdDesc() {
        return ResultUtil.success(userJpaRepository.findAllByRelationIdIsNullOrderByIdDesc());
    }

    @RequestMapping(value = "/findAllByOrderJifenNotNullOrderByIdDesc", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台获取已有积分用户")
    public Result findAllByOrderJifenNotNullOrderByIdDesc() {
        return ResultUtil.success(userJpaRepository.findAllByOrderJifenNotNullOrderByIdDesc());
    }

    @RequestMapping(value = "/getCountNumberByTime/{id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("管理平台每日会员用户和非会员用户总数")
    public Result getCountNumberByTime(@PathVariable int id, @RequestParam String time) {
        return ResultUtil.success(userRepository.getCountNumberByTime(time, id));
    }

    @IgnoreSecurity
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation("用户端APP 中登录")
    @ResponseBody
    public Result login(@RequestBody LoginInfo loginInfo) {
        return iUserService.Login(loginInfo);
    }

    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("用户端修改密码")
    public Result updatePwd(@RequestBody LoginInfo loginInfo) {
        return iUserService.updatePwd(loginInfo.getOld(), loginInfo.getPwd(), loginInfo.getUserId());
    }



    @IgnoreSecurity
    @ApiOperation("用户端忘记密码")
    @RequestMapping(value = "/forgetPwd", method = RequestMethod.POST)
    @ResponseBody
    public Result forgetPwd(@RequestBody LoginInfo loginInfo) {
        return iUserService.forgetPwd(loginInfo.getPwd(), loginInfo.getPhone(), loginInfo.getMsg());
    }

    @IgnoreSecurity
    @ApiOperation("用户端openid登录呢")
    @RequestMapping(value = "/openid/login", method = RequestMethod.GET)
    @ResponseBody
    public Result loginByOpenId(@RequestParam String openid, @RequestParam String relation) {
        return iUserService.loginByOpenId(openid, relation);

    }

    @RequestMapping(value = "/mp/update", method = RequestMethod.POST)
    @ResponseBody
    @IgnoreSecurity
    @ApiOperation("用户端小程序更新用户信息注册")
    public Result mpUpdateUser(@RequestBody LoginInfo loginInfo) {
        return iUserService.mpUpdateUser(loginInfo);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/openid/{openid}/{relation}/{unionid}", method = RequestMethod.GET)
    @ApiOperation("用户端会员登录 未使用 在关注公众号中使用")
    @ResponseBody
    public Result loginByOpenIdWithRelation(@PathVariable String openid, @PathVariable String relation, @PathVariable String unionid) {
        return iUserService.loginByOpenIdWithRelation(openid, relation, unionid);
    }


    @IgnoreSecurity
    @ApiOperation("用户端发送验证码")
    @RequestMapping(value = "/sendMsg/{phone}/{state}", method = RequestMethod.GET)
    @ResponseBody
    public Result sendMsg(@PathVariable String phone, @PathVariable String state) {
        return iUserService.sendMsg(phone, state);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/bindOpenid", method = RequestMethod.POST)
    @ApiOperation("用户端绑定openid")
    @ResponseBody
    public Result bindOpenid(@RequestBody LoginInfo loginInfo) {
        if (StringUtils.isNotBlank(loginInfo.getOpenid())) {
            return iUserService.bindOpenid(loginInfo);
        } else {
            return iUserService.loginCode(loginInfo);
        }
    }


    @IgnoreSecurity
    @RequestMapping(value = "/loginTaoBao", method = RequestMethod.POST)
    @ApiOperation("用户端淘宝登录绑定手机号")
    @ResponseBody
    public Result loginTaoBao(@RequestBody LoginInfo loginInfo) {
        return iUserService.loginTaoBao(loginInfo);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/loginWeiXinApp", method = RequestMethod.POST)
    @ApiOperation("用户端微信登录绑定手机号")
    @ResponseBody
    public Result loginWeiXinApp(@RequestBody LoginInfo loginInfo) {
        return iUserService.loginWeiXinApp(loginInfo);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/bindTaoBao", method = RequestMethod.POST)
    @ApiOperation("用户端手机号账号绑定淘宝")
    @ResponseBody
    public Result bindTaoBao(@RequestBody LoginInfo loginInfo) {
        return iUserService.bindTaoBao(loginInfo);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/loginApp", method = RequestMethod.POST)
    @ApiOperation("用户端使用微信登录")
    @ResponseBody
    public Result loginApp(@RequestBody LoginInfo loginInfo) {
        return iUserService.loginApp(loginInfo);
    }

    @IgnoreSecurity
    @RequestMapping(value = "/loginTb", method = RequestMethod.POST)
    @ApiOperation("用户端使用淘宝登录")
    @ResponseBody
    public Result loginTb(@RequestBody LoginInfo loginInfo) {
        return iUserService.loginTb(loginInfo);
    }

    @RequestMapping(value = "/updatePhone", method = RequestMethod.POST)
    @ApiOperation("用户端换绑手机号")
    @ResponseBody
    public Result updatePhone(@RequestParam String phone, @RequestParam String msg, @RequestParam String userId) {
        return iUserService.updatePhone(phone, msg, userId);
    }

    @RequestMapping(value = "/updateClientId", method = RequestMethod.POST)
    @ApiOperation("用户端绑定消息推送clientId")
    @IgnoreSecurity
    @ResponseBody
    public Result updateClientId(@RequestParam String clientId, @RequestParam String userId) {
        UserInfo userInfo = userJpaRepository.findById(Long.valueOf(userId)).orElse(null);
        System.out.println(clientId);
        if (userInfo != null) {
            userInfo.setClientid(clientId);
            return ResultUtil.success(userJpaRepository.save(userInfo));
        }
        return ResultUtil.error(ExceptionEnum.USER_NOT_FIND);
    }

    @RequestMapping(value = "/bindPhone", method = RequestMethod.POST)
    @ApiOperation("用户端绑定手机号")
    @ResponseBody
    public Result bindPhone(@RequestParam String phone, @RequestParam String msg, @RequestParam String userId) {
        return iUserService.bindPhone(userId, phone, msg);
    }

    @RequestMapping(value = "/updateInvitation/{userId}", method = RequestMethod.POST)
    @ApiOperation("管理平台更新用户授权状态")
    @ResponseBody
    public Result updateInvitation(@PathVariable Long userId) {
        UserInfo one = userJpaRepository.findById(userId).orElse(null);
        assert one != null;
        if (one.getIsInvitation() == 0) {
            one.setIsInvitation(1);
        } else {
            one.setIsInvitation(0);
        }
        return ResultUtil.success(userJpaRepository.save(one));
    }

    @RequestMapping(value = "/updateState/{userId}", method = RequestMethod.POST)
    @ApiOperation("管理平台更新用户的账号状态")
    @ResponseBody
    public Result updateState(@PathVariable Long userId) {
        UserInfo one = userJpaRepository.findById(userId).orElse(null);
        assert one != null;
        if (one.getState().equals("true")) {
            one.setState("false");
        } else {
            one.setState("true");
        }
        return ResultUtil.success(userJpaRepository.save(one));
    }


    @RequestMapping(value = "/updateGrades", method = RequestMethod.GET)
    @ApiOperation("管理平台修改用户等级")
    @ResponseBody
    public Result updateGrade(@RequestParam String userId, @RequestParam String grade) {
        UserInfo one = userJpaRepository.findById(Long.valueOf(userId)).orElse(null);
        assert one != null;
        one.setGrade(grade);
        one.setId(one.getId());
        return ResultUtil.success(userJpaRepository.save(one));
    }

    @RequestMapping(value = "/updateName", method = RequestMethod.GET)
    @ApiOperation("管理平台修改备注")
    @ResponseBody
    public Result updateName(@RequestParam String userId, @RequestParam String name) {
        UserInfo one = userJpaRepository.findById(Long.valueOf(userId)).orElse(null);
        assert one != null;
        one.setName(name);
        one.setId(one.getId());
        return ResultUtil.success(userJpaRepository.save(one));
    }

    @RequestMapping(value = "/bind/relationId/{relationId}/{userid}", method = RequestMethod.GET)
    @ApiOperation("用户端绑定渠道")
    @ResponseBody
    public Result bindRelationId(@PathVariable String relationId, @PathVariable String userid) {
        return iUserService.bindRelationId(userid, relationId);
    }

    @RequestMapping(value = "/bind/relationCode/{relationId}/{userid}/{code}", method = RequestMethod.GET)
    @ApiOperation("用户端获取渠道")
    @ResponseBody
    public Result bindRelationIdCode(@PathVariable String relationId, @PathVariable String userid, @PathVariable String code) {
        return iUserService.bindRelationIdCode(userid, relationId, code);
    }

    @RequestMapping(value = "/bind/openid/{openid}/{userid}", method = RequestMethod.GET)
    @ApiOperation("用户端绑定opneid")
    @ResponseBody
    public Result bindOpenId(@PathVariable String openid, @PathVariable String userid) {
        return iUserService.bindOpenId(userid, openid);
    }

    @RequestMapping(value = "/userinfo/{userId}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("用户端获取用户信息")
    @LoginRequired
    public Result getUserInfo(@PathVariable String userId) {
        return iUserService.findOne(Long.valueOf(userId));
    }

    @RequestMapping(value = "/userList", method = RequestMethod.GET)
    @ApiOperation("管理平台获取用户列表")
    @ResponseBody
    public Result getUserList(@RequestParam String phone, @RequestParam Integer page, @RequestParam int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        if (!phone.isEmpty() && !phone.equals("undefined")) {
            return iUserService.find(phone, pageable);
        } else {
            return iUserService.findList(pageable);
        }
    }

    @RequestMapping(value = "/getUsersByInvitation", method = RequestMethod.GET)
    @ApiOperation("管理平台获取邀请用户列表")
    @ResponseBody
    public Result getUsersByInvitation(@RequestParam String invitation, @RequestParam Integer page, @RequestParam int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return iUserService.getUsersByInvitation(invitation, pageable);
    }

    @RequestMapping(value = "/getInvitation", method = RequestMethod.GET)
    @ApiOperation("管理平台获取邀请用户用户列表")
    @ResponseBody
    public Result getInvitation(@RequestParam String invitation) {
        return iUserService.getInvitation(invitation);
    }

    @RequestMapping(value = "/getInvitations/{invitation}/{page}/{size}", method = RequestMethod.GET)
    @ApiOperation("管理平台获取邀请用户用户列表")
    @ResponseBody
    public Result getInvitations(@PathVariable("invitation") String invitation,@PathVariable("page") int page,@PathVariable("size") int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(userRepository.getInvitations(invitation,pageable));
    }

    @IgnoreSecurity
    @RequestMapping(value = "/getInvitations/{invitation}/{page}/{size}/{type}", method = RequestMethod.GET)
    @ApiOperation("管理平台获取邀请用户用户列表")
    @ResponseBody
    public Result getInvitations(@PathVariable("invitation") String invitation,@PathVariable("page") int page,@PathVariable("size") int size,@PathVariable("type") int type) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        if(type==1){
            return ResultUtil.success(userRepository.getInvitations(invitation,pageable));
        }else{
            return ResultUtil.success(userRepository.getInvitationss(invitation,pageable));
        }
    }

    @RequestMapping(value = "/getCount", method = RequestMethod.GET)
    @ApiOperation("管理平台和用户获取邀请用户用户列表")
    @ResponseBody
    public Result getCount(@RequestParam String invitation) {
        return ResultUtil.success(userRepository.getCounts(invitation));
    }

    @RequestMapping(value = "/getCash", method = RequestMethod.GET)
    @ApiOperation("管理平台获取邀请用户用户列表")
    @ResponseBody
    public Result getCash(@RequestParam String invitation) {
        return iUserService.getCash(invitation);
    }

    @RequestMapping(value = "/relationId", method = RequestMethod.GET)
    @ApiOperation("用户端通过渠道id获取用户信息")
    @ResponseBody
    public Result getUserBuyRelation(@RequestParam String relationId) {
        return ResultUtil.success(userRepository.getUserByRelationId(relationId));
    }

    @RequestMapping(value = "/checkRelationInvitations", method = RequestMethod.GET)
    @ResponseBody
    @IgnoreSecurity
    public Result checkRelationInvitations(@RequestParam String invitation, @RequestParam String userOpenid, @RequestParam String phone) {
        return ResultUtil.success(iUserService.checkRelationInvitations(invitation, userOpenid, phone));
    }

    @RequestMapping(value = "/userList/{page}/{size}", method = RequestMethod.GET)
    @ApiOperation("管理平台多条件查询语句")
    @ResponseBody
    public Result userList(@PathVariable int page, @PathVariable int size, @RequestParam String phone, @RequestParam String platform, @RequestParam int isRelation, @RequestParam int isTuan, @RequestParam(required = false, defaultValue = "-1") String nickName) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        // 构造自定义查询条件
        Specification<UserInfo> queryCondition = new Specification<UserInfo>() {
            @Override
            public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (!platform.equals("all")) {
                    predicateList.add(criteriaBuilder.equal(root.get("platform"), platform));
                }
                if (!phone.equals("-1")) {
                    predicateList.add(criteriaBuilder.equal(root.get("phone"), phone));
                }
                if (!nickName.equals("-1")) {
                    predicateList.add(criteriaBuilder.like(root.get("nickName"), "%" + nickName + "%"));
                }
                /*if (isRelation != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("isRelation"), isRelation));
                }*/
                if (isRelation == 1) { //会员用户
                    predicateList.add(criteriaBuilder.isNotNull(root.get("gradeIndex")));
                }else if ( isRelation == 0){ //普通用户
                    predicateList.add(criteriaBuilder.isNull(root.get("gradeIndex")));
                }
                if (isTuan != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("isTuan"), isTuan));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(userJpaRepository.findAll(queryCondition, pageable));
    }

    /**
     * 获取用户邀请人
     *
     * @return
     */
    @RequestMapping(value = "/team/users/{relation}", method = RequestMethod.GET)
    @ApiOperation("获取用户邀请人")
    @ResponseBody
    public Result getTeamTotal(@PathVariable String relation) {
        List<invitationTotal> list = new ArrayList<>();
        List<Long> usersByInvitations = userRepository.getUsersByRelationId(relation);
        List<UserInfo> allUser = userJpaRepository.findAll();
        for (Long usersByInvitation : usersByInvitations) {
            UserInfo byId = new UserInfo();
            for (UserInfo u : allUser) {
                if (usersByInvitation == u.getId()){
                    byId = u;
                }
            }
            //UserInfo byId = userJpaRepository.findById(usersByInvitation).orElse(null);
            invitationTotal invitationTotal = new invitationTotal();
            assert byId != null;
            invitationTotal.setGrade(byId.getRelationId());
            invitationTotal.setTime(byId.getCreateAt());
            if (byId.getNickName() != null) {
                invitationTotal.setUserName(byId.getNickName());
            } else {
                invitationTotal.setUserName(byId.getPhone());
            }
            if (StringUtils.isNotBlank(byId.getRelationId())) {
                invitationTotal.setMoney(0);
            } else {
                invitationTotal.setMoney(0);
            }
            if (invitationTotal.getUserName() == null) {
                invitationTotal.setUserName("用户："+byId.getId());
            }
            list.add(invitationTotal);
        }
        List<invitationTotal> sortDesList = list.stream().sorted(Comparator.comparingInt(invitationTotal::getMoney).reversed()).collect(Collectors.toList());
        sortDesList.stream().forEach(s -> System.out.println(s.getMoney()));
        return ResultUtil.success(sortDesList);
    }

    private void totalSuccess(String openId, String name, String date, String money, String totalMoney, String url) {
        try{
            UserInfo userByWxId = userRepository.getUserByWxId(openId);
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState(String.valueOf(4));
            messageInfo.setContent(name + " 您好！您上月【确认收货订单】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现，提现周期到【下个月25号】,过期清零哦");
            messageInfo.setTitle("本月结算通知");
            messageInfo.setUserName(userByWxId.getNickName());
            messageInfo.setUserId(String.valueOf(userByWxId.getId()));
            iMessageService.saveBody(messageInfo);
            if (userByWxId.getClientid() != null) {
                userService.pushToSingle("本月结算通知", name + " 您好！您上月【确认收货订单】结算信息如下，请尽快申请提现！结算金额【" + money + "】进入【我的】点击【可提现金额】申请提现，提现周期到【下个月25号】,过期清零哦", userByWxId.getClientid());
            }
            CommonInfo three = commonRepository.findOne(37);
            String apkey = Config.JieSuanNotification;
            if (three != null) {
                apkey = three.getValue();
            }
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("first", new TemplateMessageItem(name + " 您好！您上月【确认收货订单】已经结算，请尽快申请提现", "#d71345"));
            data.put("keyword1", new TemplateMessageItem(date, "#d71345"));
            data.put("keyword2", new TemplateMessageItem(money + " 元", "#d71345"));
            data.put("keyword3", new TemplateMessageItem(totalMoney + " 元", "#d71345"));
            data.put("remark", new TemplateMessageItem("点击【查看详情】进入【我的】点击【可提现金额】申请提现，提现周期到【下个月25号】,过期清零哦，如有疑问请在公众号中发送您的问题联系客服", null));
            accountService.sendWxMessage(apkey, data, openId, url);

        }catch (Exception e){

        }
        }

    @ApiOperation("二维码生成")
    @GetMapping(value = "/getImg")
    @IgnoreSecurity
    public void getImg(@RequestParam(required = false) String page,@RequestParam(required = false) String scene, @RequestParam String width,HttpServletResponse response) {
        iUserService.getImg(page, scene, width, response);
    }

    @ApiOperation("二维码生成")
    @GetMapping(value = "/getImgPath")
    @IgnoreSecurity
    public Result<String> getImgPath(@RequestParam(required = false) String page,@RequestParam(required = false) String scene, @RequestParam String width) throws Exception{
        String path = iUserService.getImagePath(page, scene, width);
        return ResultUtil.success(path);
    }

    @PostMapping("/updateNickName")
    @ApiOperation("修改用户名")
    @ResponseBody
    public Result updateNickName(Long userId,String nickName){
        Integer integer = userRepository.updateNickName(nickName, userId);
        if(integer>0){
            return ResultUtil.success();
        }
        return ResultUtil.error(-100,"修改失败，刷新页面后重试！");
    }

    @PostMapping("/updateImgUrl")
    @ApiOperation("修改头像")
    @ResponseBody
    public Result updateImgUrl(Long userId,String imgUrl){
        Integer integer = userRepository.updateImgUrl(imgUrl, userId);
        if(integer>0){
            return ResultUtil.success();
        }
        return ResultUtil.error(-100,"修改失败，刷新页面后重试！");
    }

    @PostMapping("/updateUserBank")
    @ApiOperation("修改银行卡信息")
    @ResponseBody
    public Result updateUserBank(Long userId,String bankCard,String bankCardName,String bankCarUserName){
        UserInfo userById = userRepository.getUserById(userId);
        userById.setBankCard(bankCard);
        userById.setBankCardName(bankCardName);
        userById.setBankCarUserName(bankCarUserName);
        userJpaRepository.save(userById);
        return ResultUtil.success();
    }

    @PostMapping("/updateUserMoneys")
    @ApiOperation("修改用户金额")
    public Result updateUserMoneys(Long userId, Integer type, String money){
        MoneyDetails moneyDetails = new MoneyDetails();
        moneyDetails.setClassify(1);
        moneyDetails.setUserId(userId);

        if(type==1){
            userRepository.updateJiFenAdd(money, userId);
            moneyDetails.setType(1);
            moneyDetails.setTitle("系统增加金额");
            moneyDetails.setContent("系统增加金额："+money);
        }else{
            userRepository.updateJiFenDelete(money, userId);
            moneyDetails.setType(2);
            moneyDetails.setTitle("系统减少金额");
            moneyDetails.setContent("系统减少金额："+money);
        }
        moneyDetails.setMoney(Double.parseDouble(money));
        moneyDetails.setCreateTime(DateUtil.createTime());
        moneyDetailsJpaRepository.save(moneyDetails);
        return ResultUtil.success();
    }




}
